<template>
  <view class="technique-page">

    <!-- 搜索栏 -->
    <view class="search-section">
      <view class="search-bar">
        <text class="search-icon">Q</text>
        <input 
          class="search-input" 
          placeholder="请输入标题搜索" 
          v-model="searchKeyword"
          @input="onSearchInput"
        />
      </view>
      <view class="publish-btn" @click="publishDocument">
        发布+
      </view>
    </view>

    <!-- 分类标签 -->
    <view class="category-section">
      <scroll-view class="category-scroll" scroll-x="true">
        <view class="category-list">
          <view 
            class="category-item" 
            :class="{ active: currentCategory === item.id }"
            v-for="item in categoryList" 
            :key="item.id"
            @click="selectCategory(item.id)"
          >
            {{ item.name }}
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 文档列表 -->
    <view class="document-section">
      <view class="document-list">
        <view 
          class="document-item" 
          v-for="item in documentList" 
          :key="item.id"
          @click="openDocument(item)"
        >
          <view class="file-icon" :class="'file-' + (item.fileExt ? item.fileExt.toLowerCase() : 'default')">
            <text class="file-type-text">{{ getFileTypeText(item.fileExt) }}</text>
          </view>
          <view class="document-info">
            <view class="document-title">{{ item.fileName }}</view>
            <view class="document-meta">{{ item.createTime }}发布</view>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore" @click="loadMore">
        <text class="load-more-text">加载更多</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="documentList.length === 0 && !loading">
        <text class="empty-text">暂无文档</text>
      </view>
    </view>

    <!-- 加载状态 -->
    <view class="loading" v-if="loading">
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script>
import { getTechWikiFileList } from '@/api/api.js'

export default {
  name: 'TechniqueCenter',
  data() {
    return {
      searchKeyword: '',
      currentCategory: 'all', // 当前选中的分类ID
      categoryList: [
        { id: 'all', name: '全部' }
      ],
      documentList: [],
      loading: false,
      hasMore: true,
      currentPage: 1,
      pageSize: 20
    }
  },
  onLoad() {
    this.loadCategories()
    this.loadDocuments()
  },
  methods: {
    // 发布文档
    publishDocument() {
      uni.navigateTo({
        url: '/pages/technique/techniqueCenter/detail'
      })
    },

    // 搜索输入
    onSearchInput() {
      // 防抖处理
      clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.searchDocuments()
      }, 500)
    },

    // 选择分类
    selectCategory(categoryId) {
      this.currentCategory = categoryId
      this.currentPage = 1
      this.documentList = []
      this.loadDocuments()
    },

    // 打开文档
    openDocument(document) {
      uni.navigateTo({
        url: `/pages/technique/techniqueCenter/documentDetails?id=${document.id}&fileName=${encodeURIComponent(document.fileName)}&filePath=${encodeURIComponent(document.filePath)}`
      })
    },

    // 获取文件类型样式类
    getFileTypeClass(fileExt) {
      const typeMap = {
        'doc': 'file-word',
        'docx': 'file-word',
        'pdf': 'file-pdf',
        'ppt': 'file-ppt',
        'pptx': 'file-ppt',
        'xls': 'file-excel',
        'xlsx': 'file-excel',
        'txt': 'file-text',
        'zip': 'file-zip',
        'rar': 'file-zip'
      }
      return typeMap[fileExt?.toLowerCase()] || 'file-default'
    },

    // 获取文件类型文本
    getFileTypeText(fileExt) {
      const typeMap = {
        'doc': 'W',
        'docx': 'W',
        'pdf': 'PDF',
        'ppt': 'PPT',
        'pptx': 'PPT',
        'xls': 'X',
        'xlsx': 'X',
        'txt': 'T',
        'zip': 'Z',
        'rar': 'R'
      }
      return typeMap[fileExt?.toLowerCase()] || '?'
    },

    // 加载分类列表
    async loadCategories() {
      try {
        // TODO: 调用后端API获取分类列表
        // const response = await this.$api.getCategories()
        // this.categoryList = [
        //   { id: 'all', name: '全部' },
        //   ...response.data
        // ]
        
        // 模拟API调用
      } catch (error) {
        console.error('加载分类失败:', error)
        uni.showToast({
          title: '加载分类失败',
          icon: 'none'
        })
      }
    },

    // 加载文档列表
    async loadDocuments() {
      if (this.loading) return
      
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          limit: this.pageSize
        }
        
        // 添加搜索关键词
        if (this.searchKeyword.trim()) {
          params.keywords = this.searchKeyword.trim()
        }
        
        // 添加文件类型筛选
        if (this.currentCategory !== 'all') {
          params.fileTypeId = this.currentCategory
        }
        
        const response = await getTechWikiFileList(params)
        
        if (response.code === 200) {
          const { list, totalPage } = response.data
          
          if (this.currentPage === 1) {
            this.documentList = list || []
            // 提取唯一的fileTypeName作为分类选项
            this.updateCategoryList(list || [])
          } else {
            this.documentList = [...this.documentList, ...(list || [])]
          }
          
          // 判断是否还有更多数据
          this.hasMore = this.currentPage < totalPage
        } else {
          uni.showToast({
            title: response.message || '加载失败',
            icon: 'none'
          })
        }
        
      } catch (error) {
        console.error('加载文档失败:', error)
        uni.showToast({
          title: '加载文档失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    // 搜索文档
    async searchDocuments() {
      this.currentPage = 1
      this.documentList = []
      this.loadDocuments()
    },

    // 加载更多
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.currentPage++
        this.loadDocuments()
      }
    },
    
    // 更新分类列表
    updateCategoryList(documentList) {
      const uniqueTypes = new Map()
      
      // 提取唯一的fileTypeName和fileTypeId
      documentList.forEach(item => {
        if (item.fileTypeName && item.fileTypeId) {
          uniqueTypes.set(item.fileTypeId, item.fileTypeName)
        }
      })
      
      // 构建分类列表
      const categories = [{ id: 'all', name: '全部' }]
      uniqueTypes.forEach((name, id) => {
        categories.push({ id: id.toString(), name })
      })
      
      this.categoryList = categories
    }
  }
}
</script>

<style scoped>
.technique-page {
  background-color: #F5F5F5;
  min-height: 100vh;
  position: relative;
}


/* 搜索栏 */
.search-section {
  display: flex;
  align-items: center;
  padding: 20rpx 32rpx;
  background-color: #FFFFFF;
  gap: 16rpx;
}

.search-bar {
  display: flex;
  align-items: center;
  background-color: #F8F8F8;
  border-radius: 24rpx;
  padding: 16rpx 24rpx;
  flex: 1;
}

.search-icon {
  font-size: 32rpx;
  color: #999999;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333333;
  background: transparent;
  border: none;
  outline: none;
}

/* 发布按钮 */
.publish-btn {
  background-color: #FF4444;
  color: #FFFFFF;
  padding: 12rpx 20rpx;
  border-radius: 16rpx;
  font-size: 24rpx;
  font-weight: bold;
  white-space: nowrap;
}

/* 分类标签 */
.category-section {
  background-color: #FFFFFF;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #F0F0F0;
}

.category-scroll {
  white-space: nowrap;
}

.category-list {
  display: flex;
  padding: 0 32rpx;
}

.category-item {
  padding: 12rpx 24rpx;
  margin-right: 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: #666666;
  background-color: transparent;
  white-space: nowrap;
  position: relative;
}

.category-item.active {
  background-color: #FF8800;
  color: #FFFFFF;
}

/* 文档列表 */
.document-section {
  background-color: #FFFFFF;
  margin-top: 20rpx;
}

.document-list {
  padding: 0 32rpx;
}

.document-item {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #F0F0F0;
}

.document-item:last-child {
  border-bottom: none;
}

.file-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;
}

.file-word {
  background-color: #2196F3;
}

.file-doc {
  background-color: #2196F3;
}

.file-docx {
  background-color: #2196F3;
}

.file-pdf {
  background-color: #F44336;
}

.file-ppt {
  background-color: #FF9800;
}

.file-pptx {
  background-color: #FF9800;
}

.file-excel {
  background-color: #4CAF50;
}

.file-xls {
  background-color: #4CAF50;
}

.file-xlsx {
  background-color: #4CAF50;
}

.file-text {
  background-color: #607D8B;
}

.file-txt {
  background-color: #607D8B;
}

.file-zip {
  background-color: #795548;
}

.file-rar {
  background-color: #795548;
}

.file-default {
  background-color: #9E9E9E;
}

.file-type-text {
  color: #FFFFFF;
  font-size: 24rpx;
  font-weight: bold;
}

.document-info {
  flex: 1;
}

.document-title {
  font-size: 28rpx;
  color: #333333;
  font-weight: bold;
  line-height: 1.4;
  margin-bottom: 8rpx;
}

.document-meta {
  font-size: 22rpx;
  color: #999999;
}

/* 加载更多 */
.load-more {
  padding: 32rpx;
  text-align: center;
}

.load-more-text {
  font-size: 26rpx;
  color: #666666;
}

/* 空状态 */
.empty-state {
  padding: 80rpx 32rpx;
  text-align: center;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}

/* 加载状态 */
.loading {
  padding: 32rpx;
  text-align: center;
}

.loading-text {
  font-size: 26rpx;
  color: #666666;
}
</style>